/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.sharedbills.shared.model.notification;

import java.io.Serializable;
import java.util.ArrayList;

public class AbstractNotifier implements Notifier, NotificationListener, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -9094702010964857584L;

	/*
	 * (non-Javadoc)
	 * @see org.jb.sharedbills.shared.model.notification.Notifier#addListener(org.jb.sharedbills.shared.model.notification.NotificationListener)
	 */
	@Override
	public void addListener(NotificationListener listener) {
		if (listeners == null) {
			listeners = new ArrayList<NotificationListener>();
		}
		
		listeners.add( listener );
		
	}

	/*
	 * 
	 */
	public boolean hasListeners() {
		return listeners != null && !listeners.isEmpty();
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.jb.sharedbills.shared.model.notification.Notifier#removeListener(org.jb.sharedbills.shared.model.notification.NotificationListener)
	 */
	@Override
	public void removeListener(NotificationListener listener) {
		if (listener == null)
			return;
		
		listeners.remove(listener);
	}
	
	/*
	 * 
	 */
	protected void doNotify( String property, Object oldValue, Object newValue ) {
		
		if (listeners == null || listeners.isEmpty())
			return;
		
		PropertyChangeNotification<Object> notification = new PropertyChangeNotification<Object>( this, property, oldValue, newValue );
		doNotify( notification );
	}
	
	/**
	 * 
	 * @param notification
	 */
	protected void doNotify( Notification notification ) {
		
		if (listeners == null || listeners.isEmpty())
			return;
		
		for( NotificationListener listener : listeners ) {
			listener.handle( notification );
		}

	}
	
	/*
	 * 
	 */
	@Override
	public void handle(Notification notification) {
		doNotify(notification);
	}
	
	private transient ArrayList<NotificationListener> listeners = null;



}
